<template>
  <div class="app">
    <h1 style="text-align: center;">个人信息</h1>
    <div class="head-img">
      <input
        type="file"
        id="upload"
        style="display:none;"
        accept="image/gif,image/jpeg,image/png,image/jpg"
        @change="freshImg"
      />
      <div class="border" @click="uploadIMg" :title="message">
        <img :src="imgsrc" class="imgDiv" />
      </div>
    </div>

    <div class="edit">
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="userinfo"
      >
        <el-form-item
          label="账号"
          prop="username"
          style="margin-left: 180px;margin-top:40px"
        >
          <el-col :span="14">
            <el-input v-model="userinfo.username" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          style="margin-left: 180px;margin-top:40px"
        >
          <el-col :span="14">
            <el-input v-model="userinfo.password" show-password disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="pnumber"
          style="margin-left: 180px;margin-top:40px"
        >
          <el-col :span="14">
            <el-input v-model="userinfo.phone" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item style="margin-left: 300px;">
          <el-button
            type="primary"
            @click="
              dialogFormVisible = true;
              handleEdit(userinfo);
            "
            >修改</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="修改个人信息" :visible.sync="dialogFormVisible">
      <el-form :model="userform" ref="userform" :rules="rules" status-icon>
        <el-form-item
          label="账号"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="userform.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="userform.password" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" :label-width="formLabelWidth">
          <el-input
            v-model.number="userform.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            dialogFormVisible = false;
            update('userform');
          "
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    let validPassword = (rule, value, callback) => {
      // let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,10}$/;
      let reg = /[0-9a-zA-Z]{3,10}$/;
      if (!reg.test(value)) {
        callback(new Error("密码必须是由3-10位字母或数字组合"));
      } else {
        callback();
      }
    };
    // { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
    let validUsername = (rule, value, callback) => {
      let reg = /[0-9a-zA-Z]{1,8}/;
      if (!reg.test(value)) {
        callback(new Error("只可以输入数字或字母(1~8位)"));
      } else {
        callback();
      }
    };
    return {
      id: localStorage.getItem("id"),
      message: "点我修改头像",
      labelPosition: "right",
      userinfo: {
        username: "123456",
        password: "123456",
        phone: ""
      },
      userform: {
        username: "123456",
        password: "123456",
        phone: ""
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,
      imgsrc: "",
      imgObj: "",
      rules: {
        username: [
          { required: true, message: "账号不可为空", trigger: "blur" },
          { validator: validUsername, trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不可为空", trigger: "blur" },
          { validator: validPassword, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不可为空", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getInfo();
    this.getImg();
  },
  methods: {
    handleEdit(user) {
      this.userform.username = localStorage.getItem("username");
      this.userform.password = '';
      this.userform.phone = localStorage.getItem("phone");
    },
    getImg() {
      let headimg = localStorage.getItem("headimg");
      if (headimg) {
        this.imgsrc = "data:image/png;base64," + headimg;
      } else {
        this.imgsrc =
          "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg"; //用户没有上传图片的默认头像
      }
    },
    uploadIMg: function() {
      document.getElementById("upload").click();
    },
    freshImg: function(e) {
      let _this = this;
      _this.imgObj = e.target.files[0]; //得到上传的第一个文件
      let img = new FormData();
      img.append("files", _this.imgObj);
      img.append("id", localStorage.getItem("id"));
      this.$axios
        .post("http://1.117.99.174:8080/newsmap/user/updateHead", img)
        .then(function(response) {
          if (response.data.code == 200) {
            localStorage.removeItem("headimg");
            localStorage.setItem("headimg", response.data.files);
            _this.imgsrc = "data:image/png;base64," + response.data.files;
            _this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
          } else {
            _this.$message({
              showClose: true,
              message: "修改失败（文件过大或不支持此格式!）",
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getInfo() {
      this.userinfo.username = localStorage.getItem("username");
      this.userinfo.password = localStorage.getItem("password");
      this.userinfo.phone = localStorage.getItem("phone");
    },
    update(formName) {
      let that = this;
      let self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let form = new FormData();
          form.append("id", that.id);
          form.append("name", that.userform.username);
          form.append("password", that.userform.password);
          form.append("pnumber", that.userform.phone);
          self.$axios
            .post("http://1.117.99.174:8080/newsmap/user/update", form)
            .then(function(response) {
              if (response.data.code == 200) {
                localStorage.setItem("username", that.userform.username);
                localStorage.setItem("password", that.userform.password);
                localStorage.setItem("phone", that.userform.phone);
                that.getInfo();
                that.$message({
                  showClose: true,
                  message: "修改成功",
                  type: "success"
                });
              } else {
                that.getInfo();
                that.$message({
                  showClose: true,
                  message: "修改失败",
                  type: "warning"
                });
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          that.$message({
            showClose: true,
            message: "请重新修改",
            type: "warning"
          });
        }
      });
    }
  }
};
</script>

<style>
.app {
  width: 50%;
  margin: auto;
}
.head-img {
  margin-top: 60px;
  text-align: center;
  margin-bottom: 0.2rem;
}
.border {
  display: inline-block;
  width: 8rem;
  height: 8rem;
  border-radius: 50%;
  border: 1px solid #c3c3c3;
  overflow: hidden;
  line-height: 5rem;
  text-align: center;
  position: relative;
}
.imgDiv {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  border-radius: 50%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  z-index: -1;
}
</style>
